import {
    getToken,
    setToken,
    removeToken
} from '@/utils/auth'
import {
    login
} from '@/api/user.js'

const getDefaultState = () => {
    return {
        token: getToken(),
        userName: '',
        avatar: '',
        userId:undefined
    }
}

const state = getDefaultState()

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, userName) => {
        state.userName = userName
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_ID:(state,userId)=>{
        state.userId = userId
    }


}

const actions = {
    login({
        commit
    }, userInfo) {
        
        const {
            userName,
            password
        } = userInfo
        return new Promise((resolve, reject) => {
            
            login({
                userName: userName.trim(),
                password: password
            }).then(response => {
                
                const {
                    data
                } = response
                commit("SET_ID",data.userId)
                commit('SET_TOKEN', data.token)
                commit('SET_NAME', data.userName)
                localStorage.setItem("zkx-token", data.token)
                setToken(data.token)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

}

export default {
    namespaced: true, // 正确写法
    state,
    mutations,
    actions
}